<?php


class wish {
	/**
	 * 心愿单首页
	 * Enter description here ...
	 */
	public function index($actId,$userName,$shareId=""){
		$cid = Session::$user['customerId'];
		$wishModel=M("wish");
		$where["d.isRemoved"]=array('eq',0);
		$where["d.deleted"]=array('eq',0);
		$where["a.wishActId"]=array('eq',$actId);
		if($shareId!=""){
			$where["a.userName"]=array('eq',$shareId);
		} else{
			$where["a.userName"]=array('eq',$userName);
		}
		$list=$wishModel->alias("a")
		->join("inner join wx_{$cid}_wish_product b on a.id=b.wishId")
		->join("inner join wx_module_product d on b.pId=d.id")
		->join("left join wx_{$cid}_user_weixin_info e on e.openid=a.userName")
		//->join("left join wx_{$cid}_module_product_order_detail f on f.pid=d.id")
		->field("a.id as wishId,d.id,d.name,d.picUrl,d.fixedPrice,d.discountedPrice,d.picUrl1,
			d.inventory,d.inventoryCount,b.wishId,b.isAdd,b.buyUserName,b.buyTime,b.buyWishText,
			(select g.nickname from wx_{$cid}_wish_product f left join wx_{$cid}_user_weixin_info g on g.openid=f.buyUserName where f.id=b.id) as shareNickName,
			(select g.headimgurl from wx_{$cid}_wish_product f left join wx_{$cid}_user_weixin_info g on g.openid=f.buyUserName where f.id=b.id) as shareHeadImgUrl
			")
		->where($where)
		->select();
		foreach($list as $key=>$value){
			$picUrl1 = json_decode($value['picUrl1'],true);
			if($picUrl1&&$picUrl1[1]){
				$list[$key]['picUrl']=$picUrl1[1]['picUrl'];
			}
		}
		if($shareId!=""){
			$result["isMe"]=0;
			$result["userInfo"]=self::getWeixinUserInfo($shareId);
			$wishInfo=self::getWish($actId,$shareId);
		} else{
			$result["isMe"]=1;
			$result["userInfo"]=self::getWeixinUserInfo($userName);
			$wishInfo=self::getWish($actId,$userName);
		}
		$result["proList"]=$list;
		if($shareId=="") {
			$proListcom=self::getWishComplete($result["proList"]);
			$result["proListcom"]=$proListcom;
			$result["proListcomCount"]=count($proListcom);
		}
		$result["shareId"]=$shareId;
		$result["actId"]=$actId;
		$result["wishConfig"]=self::getWishConfig($actId);
		$shareTitle=$result["wishConfig"]["shareTitle"];
		if(!$shareTitle){
			$shareTitle=$userName."的心愿单";
		}
		$shareTitle=preg_replace("/\{nickname\}/i",$result["userInfo"]["nickname"], $shareTitle);
		$result["wishConfig"]["shareTitle"]=$shareTitle;
		$result["customerId"]=$cid;
		$result["userName"]=$userName;
		$result["wishInfo"]=$wishInfo;
		Output::instance()->module('wish', 'index')->object($result);
	}
	/*组装已经实现的心愿*/
	public function getWishComplete($result){
		$proList=array();
		foreach ($result as $rs) {
			$buyUserName=$rs["buyUserName"];
			if($buyUserName!=""){
				$proList[$buyUserName]["nickname"]=$rs["shareNickName"];
				$proList[$buyUserName]["headimgurl"]=$rs["shareHeadImgUrl"];
				$proList[$buyUserName]["buyWishText"]=$rs["buyWishText"];
				$proList[$buyUserName]["buyTime"]=date('m-d',strtotime($rs["buyTime"]));
				$proList[$buyUserName]["proList"]=array();
				foreach ($result as $rs1) {
					if($rs1["buyUserName"]==$buyUserName){
						array_push($proList[$buyUserName]["proList"],$rs1);
					}
				}
			}
		}
		return $proList;
	}
	/*获取心愿*/
	public function getWish($actId,$userName){
		$cid = Session::$user['customerId'];
		$wishModel=M("wish");
		$where["wishActId"]=array('eq',$actId);
		if($shareId!=""){
			$where["userName"]=$shareId;
		} else{
			$where["userName"]=$userName;
		}
		$list=$wishModel->where($where)->find();
		return $list;
	}
	/*
	获取活配置
	*/
	public function getWishConfig($actId){
		$cid = Session::$user['customerId'];
		$wishActModel=M("wish_act");
		$where["deleted"]=array('eq',0);
		$where["a.id"]=array('eq',$actId);
		$result=$wishActModel->alias("a")
		->where($where)
		->find();
		return $result;
	}
	public function getWeixinUserInfo($userName){
		$customerId = Session::$user['customerId'];
		$userInfoModel=M("user_weixin_info");
		$where["openid"]=$userName;
		$userInfo=$userInfoModel->where($where)->find();
		return $userInfo;
	}
	/*创建心愿单页面*/
	public function createWish($actId,$userName) {
		$cid = Session::$user['customerId'];
		$wishActModel=M("wish_act");
		$where["a.deleted"]=array('eq',0);
		$where["d.deleted"]=array('eq',0);
		$where["d.isRemoved"]=array('eq',0);
		$where["a.id"]=array('eq',$actId);
		$list=$wishActModel->alias("a")
		->join("inner join wx_{$cid}_wish_act_tags b on a.id=b.wishActId")
		->join("inner join wx_module_product_tag_list c on c.tagId=b.proTagId")
		->join("inner join wx_module_product d on d.id=c.pid")
		->field("d.id,d.name,d.picUrl,d.fixedPrice,d.discountedPrice,d.inventoryCount,d.picUrl1")
		->where($where)
		->select();
		foreach($list as $key=>$value){
			$picUrl1 = json_decode($value['picUrl1'],true);
			if($picUrl1&&$picUrl1[1]){
				$list[$key]['picUrl']=$picUrl1[1]['picUrl'];
			}
		}
		$result["proList"]=$list;
		$result["actId"]=$actId;
		$result["wishConfig"]=self::getWishConfig($actId);
		$result["customerId"]=$cid;
		$result["userName"]=$userName;
		$UserInfo = get_UserInfo_by_fromUserName($userName);
		$result["userInfo"]=$UserInfo;
		Output::instance()->module('wish', 'createWish')->object($result);
	}
	public function saveAddr($userName,$fullName,$phone,$address){
		$userInfoModel=M("user_info");
		$condition["fromUserName"]=array('eq',$userName);
		$addr=$userInfoModel->where($condition)->find();
		$addAddrData["fullName"]=$fullName;
		$addAddrData["phone"]=$phone;
		$addAddrData["address"]=$address;
		if($addr && count($addr) >0 ) {
			$result= $userInfoModel->where($condition)->save($addAddrData);
		} else {
			$addAddrData["fromUserName"]=$userName;
			$result=  $userInfoModel->add($addAddrData);
		}
		return $result;
	}
	/*保存心愿单*/
	public function saveWish($actId,$pids,$userName,$wishText="",$fullName="",$phone="",$address="") {
		$pids=explode(',', $pids);
		$wishActModel=M("wish");
		
		$addData["userName"]=$userName;
		$addData["wishActId"]=$actId;
		$addData["wishText"]=$wishText;
		$addData["createTime"]=date('Y-m-d H:i:s');
		$addData["updateTime"]=date('Y-m-d H:i:s');
		
		$where["wishActId"]=array('eq',$actId);
		$where["userName"]=array('eq',$userName);
		
		$result=$wishActModel->where($where)->find();
		if(count($result) < 1){
			$wishId=$wishActModel->add($addData);
		} else{
			$wishId=$result["id"];
			$wishActModel->where($where)->save($addData);
		}
		self::saveAddr($userName,$fullName,$phone,$address);
		$isVal=1;
		//添加心愿商品
		$wishProModel=M("wish_product");
		foreach ($pids as $pid) {
			$where1["pId"]=array('eq',$pid);
			$where1["wishId"]=array('eq',$wishId);
			$result=$wishProModel->where($where1)->find();
			if(count($result) < 1 ){
				$addData1["pId"]=$pid;
				$addData1["wishId"]=$wishId;
				$addData1["isAdd"]=1;
				$isVal=$wishProModel->add($addData1);
			}
		}
		if($isVal) {
			Output::instance()->resultCode(code_success);
		} else{
			Output::instance()->resultCode(1,'创建失败');
		}
	}
	public function getWishById($wishId){
		$wishModel=M("wish");
		$where["id"]=array('eq',$wishId);
		$result=$wishModel->where($where)->find();
		return $result;
	}
	public function mbstringtoarray($str,$charset) {
	  $strlen=mb_strlen($str);
	  while($strlen){
	    $array[]=mb_substr($str,0,1,$charset);
	    $str=mb_substr($str,1,$strlen,$charset);
	    $strlen=mb_strlen($str);
	  }
	  return $array;
	}
	/*获取订单详情*/
	public function getOrderDetail($id,$userName,$wishId){
		$cid = Session::$user['customerId'];
		$paramsPerSOrderDetail = new stdClass();
		$paramsPerSOrderDetail->tplid =1;
		$paramsPerSOrderDetail->id = $id;
		$paramsPerSOrderDetail->noNeedJsonResult = false;
		$orderDetail = Module::callModule('product', NULL, 'getOrderDetail', $paramsPerSOrderDetail);
		$wishInfo=self::getWishById($wishId);
		$shareId=$wishInfo["userName"];
		$UserInfo = get_UserInfo_by_fromUserName($shareId);
		$mobile=$UserInfo["phone"];
		$address=$UserInfo["address"];
		$wishInfo["phone"]=$mobile;
		$wishInfo["realAddress"]=$address;
		$wishInfo["fullName"]=$UserInfo["fullName"];
		$newstr="";
		$len=strlen($mobile);
		for($i=0;$i<$len; $i++) {
			if($i>2) {
				$newstr .="*";
			} else{
				$newstr .=$mobile[$i];
			}
		}
		$wishInfo["mobile"]=$newstr;
		$newstr="";
		$address=self::mbstringtoarray($address,"utf-8");
		$len=count($address);
		for($i=0;$i<$len; $i++) {
			if($i>2) {
				$newstr .="*";
			} else{
				$newstr .=$address[$i];
			}
		}
		$wishInfo["address"]=$newstr;
		if($orderDetail && count($orderDetail)){
			$result["productList"]=$orderDetail["productList"][$id];
			$order=$orderDetail;
			$CostModel = M('module_mall_delivery_cost');
			$conditionCost["maxPrice"] = array('egt', $order["price"]);
			$cost = $CostModel->where($conditionCost)->order("maxPrice asc")->find();
			$order["cost"]=$cost["cost"];
			$order["amount"]=$order["price"]+$order["cost"];
			$result["order"]=$order;
			$result["wish"]=$wishInfo;
			$result["wishId"]=$wishId;
			$result["customerId"]=$cid;
			Output::instance()->module("wish", "order")->object($result);
		}else{
			Output::instance()->resultCode(code_system_error);
		}
	}
	/**
	 * [updateOrderInfo 心愿单支付完成回调]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function updateOrderInfo($param) {
		$cid = Session::$user['customerId'];
		$wishModel=M("wish_product");
		Session::switchCustomer(0);
		$orderModel=M("module_product_order");
		Session::switchCustomer($cid);
		$oid=$param->oid;

		$order=$orderModel->alias("a")
		->field("a.*,b.pid")
		->join("inner join wx_module_product_order_detail b on a.id=b.oid")
		->where("a.id=$oid")->select();
		
		$isVal=1;
		if($order) {
			foreach ($order as $key => $value) {
				$wishId=$value["moduleId"];
				$pid=$value["pid"];
				if(!$param->updateUser) {
					$addData["buyUserName"]=$value["fromUserName"];
					$addData["buyTime"]=date('Y-m-d H:i:s');
				} else {
					$addData["buyWishText"]=$param->wishText;
				}
				$isVal=$wishModel->where("wishId=$wishId and pId=$pid")->save($addData);
			}
		}
		return $isVal;
	}
	public function saveBuyWish($param){
		$param->updateUser=1;
		$isVal=self::updateOrderInfo($param);
		if($isVal) {
			Output::instance()->resultCode(code_success);
		}
	}
	public function getWishInfo($id,$userName){
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$orderModel=M("module_product_order");
		Session::switchCustomer($cid);
		$where["a.id"]=array('eq',$id);
		$result=$orderModel->alias("a")
		->join("inner join wx_module_product_order_detail b on a.id=b.oid")
		->join("inner join wx_{$cid}_wish_product c on c.pId=b.pid")
		->join("inner join wx_{$cid}_wish d on d.id=c.wishId")
		->field("c.*,d.wishActId")
		->where($where)->select();
		if($result && count($result) > 0) {
			return $result[0];
		}
	}
	public function successOrder($id,$userName) {
		$cid = Session::$user['customerId'];
		$wishInfo=self::getWishInfo($id,$userName);
		$buyWishText=$wishInfo["buyWishText"];
		$actId=$wishInfo["wishActId"];
		$wishId=$wishInfo["wishId"];
		$result["oid"]=$id;
		$result["wishId"]=$wishId;
		$result["buyWishText"]=$buyWishText;
		$result["customerId"]=$cid;
		$result["userName"]=$userName;
		$result["actId"]=$actId;
		Output::instance()->module("wish", "orderSuccess")->object($result);
	}
	public function getAddrEdit($userName,$actId){
		$UserInfo = get_UserInfo_by_fromUserName($userName);
		$UserInfo["actId"]=$actId;
		Output::instance()->module("wish", "address")->object($UserInfo);
	}
	public function saveAddress($userName,$fullName,$phone,$address){
		$result=self::saveAddr($userName,$fullName,$phone,$address);
		if($result) {
			Output::instance()->object(code_success);
		} else{
			Output::instance()->resultCode(1,'创建失败');
		}
	}
}